<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /* 
            时间：O(N)
            空间：O(N)
        */
        function TreeNode(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new TreeNode(1)
        var b = new TreeNode(2)
        var c = new TreeNode(5)
        var d = new TreeNode(3)
        var e = new TreeNode(4)
        var f = new TreeNode(null)
        var g = new TreeNode(6)

        a.left = b
        a.right = c
        b.left = d
        b.right = e
        c.left = f
        c.right = g

        var aa = new TreeNode(1)
        var bb = new TreeNode(null)
        var cc = new TreeNode(2)
        aa.left = bb
        aa.right = cc
        var flatten = function (root) {
            if (!root) {
                return
            }
            // 先找到左子链表和右子链表
            let leftTail = flatten(root.left)
            let rightTail = flatten(root.right)
            if (leftTail) {
                // 将左子链表的right指向root的右节点，也就是右子链表的头
                leftTail.right = root.right
                // 将root的右节点指向root的左节点
                root.right = root.left
                // 左节点改为null值
                root.left = null
            }
            if (rightTail) {
                return rightTail
            } else if (leftTail) {
                return leftTail
            } else {
                return root
            }
        };
        console.log(flatten(a));
    </script>
</body>

</html>